package com.inspectortime.domain.validate;

import org.springframework.util.StringUtils;
import org.springframework.validation.Errors;
import org.springframework.validation.ValidationUtils;
import org.springframework.validation.Validator;

import com.inspectortime.domain.User;
import com.inspectortime.repository.Repository;
import com.inspectortime.util.SpringValidatorUtils;
import com.mkode.util.java.lang.ClassUtils;

public class UserValidator implements Validator {

	private Repository repository;
	public boolean supports(Class clazz) {
		return ClassUtils.isInstanceOf(clazz, User.class);
	}

	public void validate(Object obj, Errors errors) {

		User user = (User) obj;

		ValidationUtils.rejectIfEmptyOrWhitespace(errors, "name.first",
				"required");
		ValidationUtils.rejectIfEmptyOrWhitespace(errors, "name.last",
				"required");
		ValidationUtils.rejectIfEmptyOrWhitespace(errors, "phone",
		"required");
		if (!SpringValidatorUtils.isEmptyOrWhitespace(errors, "phone")) {
			SpringValidatorUtils.rejectInvalidPhone(errors, "phone");	
		}		

		// Email validation
		ValidationUtils.rejectIfEmptyOrWhitespace(errors, "email", "required");
		if (StringUtils.hasText(user.getEmail())) {
			if (!com.inspectortime.util.ValidationUtils
					.isValidEmailAddress(user.getEmail())) {
				errors.rejectValue("email", "invalid.email");
			}
		}
		
		ValidationUtils.rejectIfEmptyOrWhitespace(errors, "emailConfirm", "required.emailConfirm");
		
		if (StringUtils.hasText(user.getEmail()) && StringUtils.hasText(user.getEmailConfirm())) {
			if (!user.getEmail().equalsIgnoreCase(user.getEmailConfirm())) {
				errors.rejectValue("emailConfirm", "noMatch.emailConfirm");
			}
		}

		// User name validation
		ValidationUtils.rejectIfEmptyOrWhitespace(errors, "userName",
		"required");

		// Password validation
		ValidationUtils.rejectIfEmptyOrWhitespace(errors, "password",
		"required");
		SpringValidatorUtils.rejectInvalidPassword(errors, "password");
		
		// Validate for duplicates unless there is no change
		if (user.getOldEmail() == null || !user.getOldEmail().equals(user.getEmail())) {
			if (repository.findUserByEmail(user.getEmail()) != null) {
				errors.rejectValue("email", "duplicate");
			}			
		}
		
		// Validate unless no change
		if (user.getOldUserName() == null || !user.getOldUserName().equals(user.getUserName())) {
			if (StringUtils.hasText(user.getUserName())) {
				if (repository.findUserByUserName(user.getUserName()) != null) {
					errors.rejectValue("userName", "duplicate");
				}
			}			
		}
	}

	public void setRepository(Repository repository) {
		this.repository = repository;
	}

}
